<template>
    <page-container title="用户管理">
        <!-- 表单 -->
        <template #default>
            <el-form inline="true" ref="formModel" :model="form">
                <el-form-item label="用户昵称">
                    <el-input v-model="params.nickName" placeholder="请您输入要搜索的用户昵称" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSearch" plain>搜索</el-button>
                    <el-button @click="onReset" plain type="info">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table height="526px" :data="userList" v-loading="loading" class="el-table">
                <el-table-column label="用户id" width="180px">
                    <template #default="{ row }">
                        {{ maskUserId(row.userId) }}
                    </template>
                </el-table-column>
                <el-table-column label="用户账号" width="140px">
                    <template #default="{ row }">
                        {{ maskAccount(row.userAccount) }}
                    </template>
                </el-table-column>
                <el-table-column prop="nickName" label="用户昵称" />
                <el-table-column prop="roleNames" label="角色" min-width="200">
                    <template #default="{ row }">
                        <el-tooltip :content="row.roleNames || '无'" placement="top">
                            <span class="role-text" @click="showRoleDialog(row)">
                                {{ (row.roleNames && row.roleNames.length > 15) ?
                                    row.roleNames.substring(0, 15) + '...' :
                                    (row.roleNames || '无') }}
                            </span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="手机号" width="120px">
                    <template #default="{ row }">
                        {{ maskPhone(row.phoneNumber) }}
                    </template>
                </el-table-column>
                <el-table-column label="邮箱" width="120px">
                    <template #default="{ row }">
                        {{ maskEmail(row.emailAddress) }}
                    </template>
                </el-table-column>

                <el-table-column prop="status" width="90px" align="center" label="用户状态">
                    <template #default="{ row }">
                        <el-tag type="success" v-if="row.status">正常</el-tag>
                        <el-tag type="error" v-else>拉黑</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80px" fixed="right">
                    <template #default="{ row }">
                        <el-button class="red" v-if="row.status == 1" type="text" plain
                            @click="onUpdateUserStatus(row.userId, 0)">拉黑</el-button>
                        <el-button v-if="row.status == 0" type="text" plain
                            @click="onUpdateUserStatus(row.userId, 1)">解禁</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination small v-model:current-page="params.pageNum" v-model:page-size="params.pageSize"
                :page-sizes="[5, 10, 15, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                style="margin-top: 20px; justify-content: flex-end" />

            <!-- 角色管理弹窗 -->
            <el-dialog v-model="roleDialogVisible" title="角色管理" width="60%">
                <el-form inline="true" style="margin-bottom: 20px">
                    <el-form-item style="margin-right: 20px">
                        <el-input v-model="roleInputValue" placeholder="请输入角色名称" style="width: 240px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onRoleSearch">搜索</el-button>
                        <el-button @click="onRoleReset">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-tabs @tab-click="handleTabClick">
                    <el-tab-pane label="已关联角色">
                        <el-table :data="associatedRoleList" border>
                            <el-table-column prop="roleName" label="角色名" width="180" />
                            <el-table-column prop="createTime" label="创建时间" width="180">
                                <template #default="{ row }">
                                    {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template #default="{ row }">
                                    <el-button type="text" class="red" @click="handleRemoveRole(row)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                            :total="associatedRoleTotal" v-model:current-page="associatedRoleParams.pageNum"
                            v-model:page-size="associatedRoleParams.pageSize" :page-sizes="[5, 10, 15, 20]"
                            @size-change="handleAssociatedRoleSizeChange"
                            @current-change="handleAssociatedRolePageChange" />
                    </el-tab-pane>
                    <el-tab-pane label="可关联角色">
                        <el-table :data="availableRoleList" border>
                            <el-table-column prop="roleName" label="角色名" width="180" />
                            <el-table-column prop="createTime" label="创建时间" width="180">
                                <template #default="{ row }">
                                    {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100">
                                <template #default="{ row }">
                                    <el-button type="text" @click="handleAddRole(row)">添加</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination background layout="total, sizes, prev, pager, next, jumper"
                            :total="availableRoleTotal" v-model:current-page="availableRoleParams.pageNum"
                            v-model:page-size="availableRoleParams.pageSize" :page-sizes="[5, 10, 15, 20]"
                            @size-change="handleAvailableRoleSizeChange"
                            @current-change="handleAvailableRolePageChange" />
                    </el-tab-pane>
                </el-tabs>
            </el-dialog>
        </template>
    </page-container>
</template>

<script setup>
import { ref, computed } from 'vue';
import {
    getUserListService, updateStatusService, getUserRoleListService,
    getAvailableRolesService,
    addUserRoleService,
    removeUserRoleService
} from '@/apis/cuser'
import { reactive } from "vue";
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

const activeTab = ref('已关联角色')
const roleInputValue = computed({
    get() {
        return activeTab.value === '已关联角色'
            ? associatedRoleParams.roleName
            : availableRoleParams.roleName
    },
    set(value) {
        if (activeTab.value === '已关联角色') {
            associatedRoleParams.roleName = value
        } else {
            availableRoleParams.roleName = value
        }
    }
})

const params = ref({
    pageNum: 1,
    pageSize: 10,
    userId: '',
    userAccount: '',
    nickName: '',
    roleNames: '',
})

const updateStatusParams = ref({
    userId: '',
    status: '',
})

const userList = ref([])
const total = ref(0)
const loading = ref(false)
const roleDialogVisible = ref(false)
const currentUserId = ref('')

// 已关联角色相关
const associatedRoleList = ref([])
const associatedRoleTotal = ref(0)
const associatedRoleParams = reactive({
    pageNum: 1,
    pageSize: 10,
    userId: '',
    roleName: '',
    userAccount: '',
})

// 可关联角色相关
const availableRoleList = ref([])
const availableRoleTotal = ref(0)
const availableRoleParams = reactive({
    pageNum: 1,
    pageSize: 10,
    userId: '',
    roleName: ''
})

// 敏感信息脱敏处理
const maskUserId = (userId) => {
    if (!userId) return '';
    const str = userId.toString();
    if (str.length <= 4) return str;
    return `${str.substring(0, 2)}****${str.substring(str.length - 2)}`;
}

const maskAccount = (account) => {
    if (!account) return '';
    if (account.length <= 2) return account;
    return `${account.substring(0, 1)}***${account.substring(account.length - 1)}`;
}

const maskPhone = (phone) => {
    if (!phone) return '';
    if (phone.length !== 11) return phone;
    return `${phone.substring(0, 3)}****${phone.substring(7)}`;
}

const maskEmail = (email) => {
    if (!email) return '';
    const atIndex = email.indexOf('@');
    if (atIndex === -1) return email;
    const prefix = email.substring(0, atIndex);
    const suffix = email.substring(atIndex);
    if (prefix.length <= 2) return `***${suffix}`;
    return `${prefix.substring(0, 1)}***${prefix.substring(prefix.length - 1)}${suffix}`;
}

const showRoleDialog = async (user) => {
    currentUserId.value = user.userId
    associatedRoleParams.userId = user.userId
    availableRoleParams.userId = user.userId

    try {
        await Promise.all([
            getAssociatedRoles(),
            getAvailableRoles()
        ])
        roleDialogVisible.value = true
    } catch (error) {
        ElMessage.error('获取角色列表失败')
    }
}

// 获取已关联角色
const getAssociatedRoles = async () => {
    try {
        const result = await getUserRoleListService(associatedRoleParams)
        associatedRoleList.value = result.rows
        associatedRoleTotal.value = result.total
    } catch (error) {
        console.error('获取已关联角色失败:', error)
        throw error
    }
}

// 获取可关联角色
const getAvailableRoles = async () => {
    try {
        const result = await getAvailableRolesService(availableRoleParams)
        availableRoleList.value = result.rows
        availableRoleTotal.value = result.total
    } catch (error) {
        console.error('获取可关联角色失败:', error)
        throw error
    }
}

// 添加角色
const handleAddRole = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定添加该角色吗?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }
        )

        await addUserRoleService({
            userId: currentUserId.value,
            roleId: row.roleId
        })

        ElMessage.success('添加成功')
        await Promise.all([
            getAssociatedRoles(),
            getAvailableRoles(),
            getUserList() // 刷新用户列表
        ])
    } catch (error) {
        if (error !== 'cancel') {
            console.error('添加角色失败:', error)
            ElMessage.error(error.message || '添加失败')
        }
    }
}

// 移除角色
const handleRemoveRole = async (row) => {
    try {
        await ElMessageBox.confirm(
            '确定移除该角色吗?',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        await removeUserRoleService({
            userId: currentUserId.value,
            roleId: row.roleId
        })

        ElMessage.success('移除成功')
        await Promise.all([
            getAssociatedRoles(),
            getAvailableRoles(),
            getUserList() // 刷新用户列表
        ])
    } catch (error) {
        if (error !== 'cancel') {
            console.error('移除角色失败:', error)
            ElMessage.error(error.message || '移除失败')
        }
    }
}

// 分页处理
const handleAssociatedRoleSizeChange = (newSize) => {
    associatedRoleParams.pageNum = 1
    associatedRoleParams.pageSize = newSize
    getAssociatedRoles()
}

const handleAssociatedRolePageChange = (newPage) => {
    associatedRoleParams.pageNum = newPage
    getAssociatedRoles()
}

const handleAvailableRoleSizeChange = (newSize) => {
    availableRoleParams.pageNum = 1
    availableRoleParams.pageSize = newSize
    getAvailableRoles()
}

const handleAvailableRolePageChange = (newPage) => {
    availableRoleParams.pageNum = newPage
    getAvailableRoles()
}

// 搜索和重置
const onRoleSearch = async () => {
    if (activeTab.value === '已关联角色') {
        associatedRoleParams.pageNum = 1
        await getAssociatedRoles()
    } else {
        availableRoleParams.pageNum = 1
        await getAvailableRoles()
    }
}

const onRoleReset = async () => {
    if (activeTab.value === '已关联角色') {
        associatedRoleParams.pageNum = 1
        associatedRoleParams.roleName = ''
        await getAssociatedRoles()
    } else {
        availableRoleParams.pageNum = 1
        availableRoleParams.roleName = ''
        await getAvailableRoles()
    }
}

const handleTabClick = (tab) => {
    activeTab.value = tab.props.label
    if (tab.props.label === '可关联角色') {
        getAvailableRoles()
    } else {
        getAssociatedRoles()
    }
}

// 用户列表相关方法
const getUserList = async () => {
    const ref = await getUserListService(params.value)
    userList.value = ref.rows
    total.value = ref.total
}

const onSearch = async () => {
    loading.value = true
    params.value.pageNum = 1
    await getUserList()
    loading.value = false
}

const onReset = async () => {
    loading.value = true
    params.value.pageNum = 1
    params.value.userId = ''
    params.value.userAccount = ''
    params.value.nickName = ''
    await getUserList()
    loading.value = false
}

const onUpdateUserStatus = async (userId, status) => {
    loading.value = true
    updateStatusParams.value.userId = userId
    updateStatusParams.value.status = status
    await updateStatusService(updateStatusParams.value)
    await getUserList()
    loading.value = false
}

// 初始化获取用户列表
getUserList()
</script>

<style lang="scss" scoped>
.block-span {
    display: block;
}

.role-text {
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}
</style>